/*
 * @Description: 原文挂接
 * @Author: Rfan
 * @Date: 2022-05-04 19:07:54
 * @LastEditTime: 2022-09-08 14:13:47
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Form, Input, message, Modal, Select, Space } from 'antd';
import { fetchMetadata } from '@/api/metadata';
import { createExportItem, fetchDiskTypeList, ICreateExportParams } from '@/api/archives/export';
import { formatDate, jsonClone } from '@/utils';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import CDTypeMgtDialog from './CDTypeMgt';
import TransferTemplate from '@/components/TransferTemplate';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { IMetadata } from '@/interfaces/metadata';
import type { IBaseProp } from '../../index';
import { EnumExportBusType, EnumReceiveTypes } from '@/dictionary/transfer';
import { EnumTemplateTypes } from '@/view/system/TemplateManage/dictionaries';

interface ExportCDDialogProps extends ICommonDialog {
  info: IBaseProp;
  selectItems: number[];
}

const { Option } = Select;

const ExportCDDialog: FC<ExportCDDialogProps> = (props) => {
  const { visible, info, selectItems, onClose } = props;
  const [form] = Form.useForm();

  const [levelMetadata, setLevelMetadata] = useState<any>({});
  // 上传文件弹窗显示标志
  const [CDTypeVisible, setCDTypeVisible] = useState(false);

  // 模板光盘列表
  const [diskList, setDiskList] = useState([]);

  useEffect(() => {
    if (visible) {
      // 获取光盘容量列表
      fetchDiskTypeList({}).then((res) => {
        setDiskList(res.data);
      });
      if (info.levelList) {
        const _list = info.levelList;
        _list.forEach((item: any) => {
          const { level } = item;
          const fieldQuery = {
            metadataFieldType: QUERY_METADATA_ALL,
            coordinate: {
              atType: info.atType,
              atCode: info.atCode,
              level
            }
          };

          !levelMetadata[level] &&
            fetchMetadata(fieldQuery).then((res: any) => {
              setLevelMetadata((state: any) => ({
                ...state,
                [level]: res.data
              }));
            });
        });
      }
    }
  }, [visible]);

  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 保存表单方法
   */
  const onFinish = (vals: any) => {
    const params: ICreateExportParams = jsonClone(vals);
    params.exportType = EnumReceiveTypes.CD;
    params.fondsId = info.fondId;
    params.archiveTypeId = info.archiveTypeId;
    params.businessType = EnumExportBusType.Export;
    params.name = `光盘导出-${formatDate(new Date(), 'YYYYMMDDHHmmss')}`;
    params.exportEntryInfo = {
      atCode: info.atCode,
      atType: info.atType,
      level: info.level,
      entryIdList: selectItems,
      searchCondition: '',
      dbName: info.dbName
    };
    // 这里写死为1
    params.exportOriginalRule.level = 1;

    createExportItem(params).then(() => {
      message.success('导出任务创建成功');
      onCancel();
    });
  };

  return (
    <Modal
      title="新增光盘格式包"
      visible={visible}
      className="create-cd-dialog"
      width={600}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="export"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          导出
        </Button>
      ]}
    >
      <Form
        form={form}
        name="FolderForm"
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 14 }}
        // initialValues={{ path: data }}
        autoComplete="off"
        onFinish={onFinish}
      >
        <Form.Item label="已选择条目">{selectItems.length}条</Form.Item>
        <Form.Item label="选择光盘容量">
          <Space>
            <Form.Item
              name="lightDiskVolumeId"
              rules={[{ required: true, message: '请选择光盘' }]}
              noStyle
            >
              <Select placeholder="请选择光盘" style={{ width: 160 }}>
                {diskList.map((item: any) => (
                  <Option key={item.id} value={item.id}>
                    {item.diskName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item noStyle>
              <Button
                onClick={() => {
                  setCDTypeVisible(true);
                }}
              >
                光盘容量配置
              </Button>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item
          name="templateId"
          label="导出字段配置"
          extra="请选择档案导出条件模板，规则模板可在“模板设计”内配置)"
          rules={[{ required: true, message: '请选择模板' }]}
        >
          <TransferTemplate tplType={EnumTemplateTypes.CDExport} />
        </Form.Item>
        <Form.Item
          label="电子原文导出配置"
          extra="根据配置解析字段（一般为文件档号）层次，并在系统执行导出时生成文件夹层级，相关电子文件放置在最后一个文件夹内。"
        >
          <Space>
            <Form.Item
              name={['exportOriginalRule', 'fieldName']}
              rules={[{ required: true, message: '请选择字段' }]}
              noStyle
            >
              <Select style={{ width: 140 }}>
                {(levelMetadata[1] || []).map((metadata: IMetadata) => (
                  <Option key={metadata.id} value={metadata.field_name}>
                    {metadata.field_desc}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item noStyle>匹配分割符</Form.Item>
            <Form.Item
              name={['exportOriginalRule', 'concatMark']}
              rules={[{ required: true, message: '请输入分隔符' }]}
              noStyle
            >
              <Input style={{ width: 60 }} />
            </Form.Item>
          </Space>
        </Form.Item>
        {/* 根据后台接口，改为与excel导出相同合适，如上 */}
        {/* <Form.Item label="导出电子原文配置" colon={false}></Form.Item>
        <Form.Item>
          <FolderOpenOutlined />
          &nbsp;&nbsp;根目录
        </Form.Item>
        <Form.List name="folderRealRuleList">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field) => {
                return (
                  <div key={field.key}>
                    <Space align="baseline">
                      <span>
                        &nbsp;
                        <EnterOutlined />
                        &nbsp;
                        <FolderOpenOutlined />
                      </span>
                      <Form.Item
                        {...field}
                        key={field.key + '-1'}
                        label="序号"
                        name={[field.name, 'sortNo']}
                        rules={[{ required: true, message: '请填写序号' }]}
                      >
                        <InputNumber />
                      </Form.Item>
                      <Form.Item {...field} key={field.key + '-2'} name={[field.name, 'regex']}>
                        <Input placeholder="填写正则表达式" />
                      </Form.Item>
                    </Space>
                  </div>
                );
              })}
              <Form.Item>
                <Space>
                  <Button
                    type="dashed"
                    icon={<PlusOutlined />}
                    disabled={fields.length >= 10}
                    onClick={() => add({ sortNo: fields.length + 1, regex: '' })}
                  >
                    增加层级
                  </Button>
                  <Button
                    type="dashed"
                    icon={<MinusOutlined />}
                    onClick={() => remove(fields.at(-1)?.name)}
                  >
                    删除层级
                  </Button>
                </Space>
              </Form.Item>
            </>
          )}
        </Form.List> */}
      </Form>
      {useMemo(
        () => (
          <CDTypeMgtDialog
            visible={CDTypeVisible}
            onClose={() => {
              setCDTypeVisible(false);
            }}
          />
        ),
        [CDTypeVisible]
      )}
    </Modal>
  );
};

export default ExportCDDialog;
